package pl.edu.pk.mech.kkbus.repository;

import java.util.logging.Logger;

import pl.edu.pk.mech.kkbus.datastore.common.SynchronizeCommon;
import pl.edu.pk.mech.kkbus.model.Pojo;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public abstract class BaseDAO {

	private static final Logger log = Logger.getLogger(BussesDAO.class.getName());
	
	  /**
	 * @param id
	 * @param entityName
	 * @return zwraca konkretna encje lub null
	 */
	public Entity getEntity(long id, String entityName) {
		  if (id == 0) return null;
		  Key key = KeyFactory.createKey(entityName, id);
		  return SynchronizeCommon.findEntity(key);
	  }
	
	/**
	 * @param pojo
	 * @param nameEntity
	 * @param referenceDAO
	 * @return zwraca true gdy update lub create zostanie poprawnie wykonany
	 */
	public boolean createOrUpdate(Pojo pojo, String nameEntity, BaseDAO referenceDAO) {
		  Entity product = getEntity(pojo.getId(), nameEntity);
		    if (product == null) {
		      log.info("--- create new property "+nameEntity);
		      product = new Entity(nameEntity);
		      referenceDAO.fillProperty(pojo, product);
		      
		    } else {
		      log.info("--- update property "+nameEntity+" the key: "+product.getKey());
		      referenceDAO.fillProperty(pojo, product);
		    }
	    return SynchronizeCommon.putEntityCacheAndStore(product);
	}
	  
	public abstract void fillProperty(Pojo pojo, Entity entity);
}
